﻿using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.SessionState;
using Meotom.Upload.v2.Data.Utilities;

namespace Meotom.Upload.v2.Services
{
    /// <summary>
    /// Summary description for Users
    /// </summary>
    public class Users : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            var strMsg = "";
            context.Response.ContentType = "text/plain";

            try
            {
                var strQuery = context.Request["action"];
                var strUserName = Common.Instance.GetUploadByUser();

                switch (strQuery)
                {
                    case "Upload":
                        {
                            if(!string.IsNullOrEmpty(context.Request.QueryString["SsId"]))
                            {
                                strUserName = context.Request.QueryString["SsId"];    
                            }

                            var rnd = new RandomStrings();
                            var jpegImageUpload = context.Request.Files["Filedata"];
                            var strFileName = rnd.GenerateRandomString(DateTime.Now) + ".jpg";
                            var objImage = new ImageUtil(jpegImageUpload.InputStream, 1024, 1024, "UploadService",
                                                         strUserName, strFileName, 100);

                            if (objImage.PublicUpload("Service upload at up.meotom.net") == "OK")
                            {
                                objImage.PublicUpload(475, 0, strFileName, 100, "");
                                objImage.PublicUpload(130, 0, strFileName, 100, "");
                                objImage.PublicUpload(100, 0, strFileName, 100, "");

                                using (var dc = new mtDBUploadDataContext())
                                {
                                    dc.CreateUpload(strFileName, strUserName, context.Request.UserHostAddress);
                                }

                                strMsg = "/Files/" + strUserName + "/" + DateTime.Now.Year + "/" +
                                         Common.Instance.Right("0" + DateTime.Now.Month, 2) + "/" +
                                         Common.Instance.Right("0" + DateTime.Now.Day, 2) + "/|" + strFileName;
                            }
                            else
                            {
                                strMsg = "Fail";
                            }
                        }
                        break;
                    case "UploadUrl":
                        {
                            if (context.Request["txtUrl"] != null)
                            {
                                var arrStr = new ArrayList();
                                foreach (var strUrl in
                                    context.Request["txtUrl"].Split(Convert.ToChar(",")).Where(strUrl => PreAdd(arrStr, strUrl)))
                                {
                                    arrStr.Add(strUrl);
                                }

                                for (var index = 0; index <= arrStr.Count - 1; index++)
                                {
                                    PreDownload(arrStr[index].ToString(), strUserName, context);
                                }
                                context.Response.Redirect("/", false);
                            }
                            else
                            {
                                context.Response.Redirect("/", false);
                            }
                        }
                        break;
                    case "CheckEmailAvaiable":
                        //strMsg = Account.Register.CheckEmailAvaiable(context.Request.QueryString["Email"]);
                        break;
                    case "CheckUserAvaiable":
                        //strMsg = Account.Register.CheckUserAvaiable(context.Request.QueryString["UserName"]);
                        break;
                    case "GetImgJson":
                        if (!string.IsNullOrEmpty(context.Request.QueryString["ImgId"]))
                        {
                            strMsg = Common.Instance.IsNumeric(context.Request.QueryString["ImgId"])
                                         ? Data.BLL.Uploads.Instance.GetImgJson(
                                             int.Parse(context.Request.QueryString["ImgId"]))
                                         : "Error";
                        }
                        else
                        {
                            strMsg = "Error";
                        }
                        break;
                    case "DeleteImage":
                        var imgId = context.Request["ImgId"];
                        strUserName = Common.Instance.GetCookie("UpSSID");

                        if (strUserName != string.Empty && imgId != null)
                        {
                            if (!Data.BLL.Uploads.Instance.DeleteTemp(int.Parse(imgId), strUserName))
                            {
                                strMsg = "Xóa không thành công !!";
                            }
                        }
                        break;
                }
                context.Response.Write(strMsg);
            }
            catch (Exception)
            {
                context.Response.Write("Error !! Plz try again letter.");
            }
        }

        public static bool PreAdd(ArrayList arrStr, string strUrl)
        {
            var b = true;
            if (arrStr.Count > 0)
            {
                for (var index = 0; index <= arrStr.Count - 1; index++)
                {
                    if (strUrl == arrStr[index].ToString())
                    {
                        b = false;
                    }
                }
            }
            return b;
        }


        public static void PreDownload(string strUrl, string strUserName, HttpContext context)
        {
            if (
                !Regex.IsMatch(strUrl,
                               "^(http|https|ftp)\\://([a-zA-Z0-9\\.\\-]+(\\:[a-zA-Z0-9\\.&%\\$\\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\\-]+\\.)*[a-zA-Z0-9\\-]+\\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\\:[0-9]+)*(/($|[a-zA-Z0-9\\.\\,\\?\\'\\\\\\+&%\\$#\\=~_\\-]+))*$"))
                return;

            var rnd = new RandomStrings();
            var strFileName = rnd.GenerateRandomString(DateTime.Now) + ".jpg";
            var strm = GetStreamCntWeb(strUrl);
            if ((strm == null)) return;

            if (!DownloadImage(strm, strUserName, strFileName, 1024)) return;
            strm = GetStreamCntWeb(strUrl);
            if (!DownloadImage(strm, strUserName, strFileName, 475)) return;
            strm = GetStreamCntWeb(strUrl);
            if (!DownloadImage(strm, strUserName, strFileName, 130)) return;
            strm = GetStreamCntWeb(strUrl);
            if (!DownloadImage(strm, strUserName, strFileName, 100)) return;

            using (var dc = new mtDBUploadDataContext())
            {
                dc.CreateUpload(strFileName, strUserName, context.Request.UserHostAddress);
            }
        }

        public static bool DownloadImage(Stream strm, string strUserName, string strFileName, int imageSize)
        {
            var b = false;
            try
            {
                var objImage = new ImageUtil(strm, 1024, 1024, "UploadService", strUserName, strFileName, 75);
                switch (imageSize)
                {
                    case 1024:
                        b = objImage.PublicUpload("Service upload at up.meotom.net") == "OK";
                        break;
                    case 475:
                        b = objImage.PublicUpload(475, 0, strFileName, 100, "") == "OK";
                        break;
                    case 130:
                        b = objImage.PublicUpload(130, 0, strFileName, 100, "") == "OK";
                        break;
                    case 100:
                        b = objImage.PublicUpload(100, 0, strFileName, 100, "") == "OK";
                        break;
                }
            }
            catch (Exception)
            {
                b = false;
            }
            return b;
        }

        public static Stream GetStreamCntWeb(string s)
        {
            try
            {
                var objWebRequest = (HttpWebRequest)WebRequest.Create(s);
                objWebRequest.Timeout = 200000;
                objWebRequest.MaximumAutomaticRedirections = 4;
                objWebRequest.MaximumResponseHeadersLength = 4;
                objWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";
                objWebRequest.Credentials = CredentialCache.DefaultCredentials;

                return objWebRequest.GetResponse().GetResponseStream();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}